package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Customer;
import cn.wolfcode.crm.domain.CustomerTransfer;
import cn.wolfcode.crm.domain.CustomerTransfer;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.CustomerMapper;
import cn.wolfcode.crm.mapper.CustomerTransferMapper;
import cn.wolfcode.crm.mapper.CustomerTransferMapper;
import cn.wolfcode.crm.qo.CustomerTransferQueryObject;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.ICustomerTransferService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CustomerTransferService implements ICustomerTransferService {
    @Autowired
    private CustomerTransferMapper customerTransferMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Override
    public void saveOrUpdate(CustomerTransfer customerTransfer) {
        //插入数据
        //拿到当前对象,设置时间和操作人
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        customerTransfer.setOperateTime(new Date());
        customerTransfer.setOperator(employee);
        // 判断是移交还是吸纳----待写
        if(customerTransfer.getNewSeller() == null){
            customerTransfer.setNewSeller(employee);
        }
        //向数据库加入数据----转交历史数据
        customerTransferMapper.insert(customerTransfer);
        //转交后 需要更新customer表里的sellerId数据
        customerMapper.updateCustomerBySellerId(
                customerTransfer.getCustomer().getId(),
                customerTransfer.getNewSeller().getId());
        //如果当前状态是2  资源池客户(吸纳按钮才有的),就改为潜在客户
        Integer status = customerTransfer.getCustomer().getStatus();
        if(status != null && status == 2){
            customerMapper.updateStatus(
                    customerTransfer.getCustomer().getId(), Customer.STATUS_POTENTIAL);
        }
    }


    @Override
    public PageInfo<CustomerTransfer> selectByQuery(CustomerTransferQueryObject queryObject) {
        //用pageInfo   调用方法
        PageHelper.startPage(queryObject.getCurrentPage(),queryObject.getPageSize(),"ct.operate_time desc");
        List<CustomerTransfer> customerTransfers = customerTransferMapper.selectByQuery(queryObject);
        return new PageInfo<>(customerTransfers);
    }
}
